from sqlalchemy import and_
from sqlalchemy.orm import Session

from apis_module.model.liker_model import LikerModel


class LikerDao:
    @classmethod
    def get_liker_list_by_uid(cls, db: Session, user_id: str) -> list[LikerModel]:
        return db.query(LikerModel).filter(LikerModel.user_id == user_id) \
            .order_by(LikerModel.like_date.desc()) \
            .all()

    @classmethod
    def get_liker_list_by_rid(cls, db: Session, reviews_id: str) -> list[LikerModel]:
        return db.query(LikerModel).filter(LikerModel.reviews_id == reviews_id) \
            .order_by(LikerModel.like_date.desc()) \
            .all()

    @classmethod
    def get_liker_by_composite_id(cls, db: Session, user_id: str, reviews_id: str) -> LikerModel:
        return db.query(LikerModel).filter(and_(LikerModel.user_id == user_id, LikerModel.reviews_id == reviews_id)).first()

    @classmethod
    def add_liker(cls, db: Session, user_id: str, reviews_id: str) -> LikerModel:
        liker = LikerModel()
        try:
            liker.user_id = user_id
            liker.reviews_id = reviews_id
            db.add(liker)
            db.commit()
            return liker
        except Exception as e:
            db.rollback()
            raise e

    @classmethod
    def del_liker(cls, db: Session, user_id: str, reviews_id: str):
        try:
            db.query(LikerModel).filter(LikerModel.reviews_id == reviews_id, LikerModel.user_id == user_id) \
                .delete()
            db.flush()
            db.commit()
            return True
        except Exception as e:
            db.rollback()
            raise e
